
from rest_framework.views import APIView
from utils.config import Config
from utils.result import R
from utils.aliverify_code import * 
from api.models import ItEduLessonVideoSet,ItEduCollectLesson,ItEduLessonWatchLog,ItEduLessonVideo,ItEduRecentLesson
from django.utils import timezone  
from datetime import timedelta


class LessonAPIView(APIView):

    """
    获取某一个标签对应的视频集合 的数据量
    """
    def get(self,request,*args, **kwargs):
        tag = request.GET.get("tag","")

        total_num = ItEduLessonVideoSet.objects.filter(tags__contains=tag,score__gte=Config.MIN_SHOW_LESSON_SET_SCORE).count()

        return R().data_result(total_num=total_num)

    """
    获取某一个标签对应的视频集合
    排序按分数的多少由大到小
    """
    def post(self,request,*args, **kwargs):
        tag = request.data.get("tag","")
        offset = request.data.get("offset",0)
        limit = request.data.get("limit",10)

        if limit > 30:
            return R.params_error().to_json_response()

        lesson_set_list = list(ItEduLessonVideoSet.objects.filter(tags__contains=tag,score__gte=Config.MIN_SHOW_LESSON_SET_SCORE).order_by("-score","-_id")[offset:offset+limit].values(
            "face_image",
            "brand",
            "title",
            "lesson_order",
            "status",
            "author__nickname",
            "_id"
        ))

        for item in lesson_set_list:
            item["join_user_num"] = ItEduCollectLesson.objects.filter(lesson_set___id=item["_id"]).count()

        return R().data_result(lesson_list=lesson_set_list)

    """
    获取视频集详细信息的接口
    """
    def put(self,request,*args, **kwargs):
        lesson_id = request.data.get("lesson_id") 
        lesson = ItEduLessonVideoSet.objects.get(pk=lesson_id)
        author = lesson.author

        # 当前视频集用户的视频集推荐（3个）
        user_lesson_list = list(ItEduLessonVideoSet.objects.filter(author=author,score__gte=Config.MIN_SHOW_LESSON_SET_SCORE).order_by("-score","-_id")[:3].values(
            "title",
            "face_image",
            "brand",
            "_id"
        ))

        for item in user_lesson_list:
            item["join_user_num"] = ItEduCollectLesson.objects.filter(lesson_set___id=item["_id"]).count()


        lesson_info = {
            "title":lesson.title,
            "brand":lesson.brand,
            "lesson_order":lesson.lesson_order.split(","),
            "createtime":lesson.createtime,
            "status":lesson.status,
            "score":lesson.score,
            "join_user_num": ItEduCollectLesson.objects.filter(lesson_set=lesson).count(),
            "tags":lesson.tags,
            "user_intro":author.intro,
            "intro":lesson.intro,
            "lessonCurriculum":lesson.lessonCurriculum,
            "referenceBook":lesson.referenceBook,
            "user_info":{
                "avatar_image":author.avatar_image,
                "score":author.score,
                "nickname":author.nickname
            },
            "user_lesson_list":user_lesson_list
        }

        return R().data_result(lesson_info=lesson_info)

        

"""
我的课程
"""
class MyLessonAPIView(APIView):

    """
    获取我的课程都数量 
    """
    def get(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")

        total_num = ItEduLessonVideoSet.objects.filter(author___id=user_pk).count()

        return R().data_result(total_num=total_num)

    """
    获取我的视频集合
    排序按时间 最新-》旧
    """
    def post(self,request,*args, **kwargs):
        offset = request.data.get("offset",0)
        limit = request.data.get("limit",10)

        user_pk = request.session.get("user_pk")

        if limit > 30:
            return R.params_error().to_json_response()

        lesson_set_list = list(ItEduLessonVideoSet.objects.filter(author___id=user_pk).order_by("-_id")[offset:offset+limit].values(
            "face_image",
            "brand",
            "title",
            "lesson_order",
            "status",
            "author__nickname",
            "_id"
        ))

        for item in lesson_set_list:
            item["join_user_num"] = ItEduCollectLesson.objects.filter(lesson_set___id=item["_id"]).count()

        return R().data_result(lesson_set_list=lesson_set_list)


"""
我收藏课程
"""
class CollectionLessonAPIView(APIView):

    """
    获取我收藏课程的数量 
    """
    def get(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")

        total_num = ItEduCollectLesson.objects.filter(collecter___id=user_pk).count()

        return R().data_result(total_num=total_num)


    """
    获取我收藏视频集合
    排序按时间 最新-》旧
    """
    def post(self,request,*args, **kwargs):
        offset = request.data.get("offset",0)
        limit = request.data.get("limit",10)

        user_pk = request.session.get("user_pk")

        if limit > 30:
            return R.params_error().to_json_response()

        lesson_set_list = list(ItEduCollectLesson.objects.filter(collecter___id=user_pk).order_by("-_id")[offset:offset+limit].values(
            "lesson_set__face_image",
            "lesson_set__brand",
            "lesson_set__title",
            "lesson_set__lesson_order",
            "lesson_set__status",
            "lesson_set__author__nickname",
            "lesson_set___id"
        ))

        for item in lesson_set_list:
            item["join_user_num"] = ItEduCollectLesson.objects.filter(lesson_set___id=item["lesson_set___id"]).count()
            # 查找当前浏览到第几集
            video_id_list = item["lesson_set__lesson_order"].split(",")
            if len(video_id_list) == 0:
                continue
            try:
                video  = ItEduLessonWatchLog.objects.filter(
                    user___id = user_pk,
                    lesson___id__in = video_id_list
                ).order_by("-_id")[-1]
            except:
                video = ItEduLessonVideo.objects.get(pk=video_id_list[0])

            for index in range(0,len(video_id_list)):
                if video_id_list[index] == video._id :
                    item["current_video_num"] = index + 1
                
        return R().data_result(lesson_set_list=lesson_set_list)



"""
我最近查看课程
"""
class RecentWatchLessonAPIView(APIView):

    """
    获取我最近观看课程的数量 
    """
    def get(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")

        two_weeks_ago = timezone.now() - timedelta(weeks=2)  
  
        total_num = ItEduRecentLesson.objects.filter(watchtime__get=two_weeks_ago,user___id=user_pk).count()

        return R().data_result(total_num=total_num)


    """
    获取我最近观看视频集合
    排序按时间 最新-》旧
    """
    def post(self,request,*args, **kwargs):
        offset = request.data.get("offset",0)
        limit = request.data.get("limit",10)

        user_pk = request.session.get("user_pk")

        if limit > 30:
            return R.params_error().to_json_response()
        
        two_weeks_ago = timezone.now() - timedelta(weeks=2)  

        lesson_set_list = list(ItEduCollectLesson.objects.filter(watchtime__get=two_weeks_ago,user___id=user_pk).order_by("-_id")[offset:offset+limit].values(
            "lesson_set__face_image",
            "lesson_set__brand",
            "lesson_set__title",
            "lesson_set__lesson_order",
            "lesson_set__status",
            "lesson_set__author__nickname",
            "lesson_set___id"
        ))

        for item in lesson_set_list:
            item["join_user_num"] = ItEduCollectLesson.objects.filter(lesson_set___id=item["lesson_set___id"]).count()
            # 查找当前浏览到第几集
            video_id_list = item["lesson_set__lesson_order"].split(",")
            if len(video_id_list) == 0:
                continue
            try:
                video  = ItEduLessonWatchLog.objects.filter(
                    user___id = user_pk,
                    lesson___id__in = video_id_list
                ).order_by("-_id")[-1]
            except:
                video = ItEduLessonVideo.objects.get(pk=video_id_list[0])

            for index in range(0,len(video_id_list)):
                if video_id_list[index] == video._id :
                    item["current_video_num"] = index + 1
                
        return R().data_result(lesson_set_list=lesson_set_list)



    